class WebSocketClient {
  constructor(url) {
    this.url = url
    this.ws = null
    this.pingTimeout = null
    this.retryInterval = 5000 // 重试间隔时间（毫秒）
    this.maxRetryCount = 10 // 最大重试次数
    this.retryCount = 0
    this.connect()
  }

  connect() {
    console.log('Attempting to connect...')
    this.ws = new WebSocket(this.url)

    this.ws.onopen = () => {
      console.log('Connected to server')
      this.retryCount = 0 // 重置重试计数器
      this.startHeartbeat()
      this.onOpen() // 用户定义的打开回调
    }

    this.ws.onmessage = (event) => {
      const message = JSON.parse(event.data)
      if (message.type === 'pong') {
        console.log('Received pong from server')
        clearTimeout(this.pingTimeout)
        this.startHeartbeat()
      } else {
        this.onMessage(message) // 用户定义的消息处理回调
      }
    }

    this.ws.onclose = () => {
      console.log('Connection closed, attempting to reconnect...')
      this.stopHeartbeat()
      this.reconnect()
    }

    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error)
      this.onError(error) // 用户定义的错误处理回调
    }
  }

  startHeartbeat() {
    this.pingTimeout = setTimeout(() => {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({ type: 'ping' }))
        this.pingTimeout = setTimeout(() => {
          console.log('Ping timeout, closing connection')
          this.ws.close()
        }, 3000) // 如果3秒内没有收到响应，则认为连接已断开
      }
    }, 30000) // 每30秒发送一次ping
  }

  stopHeartbeat() {
    clearTimeout(this.pingTimeout)
  }

  reconnect() {
    if (this.retryCount < this.maxRetryCount) {
      setTimeout(() => {
        this.retryCount++
        this.connect()
      }, this.retryInterval)
    } else {
      console.error('Max retry count reached, giving up...')
    }
  }

  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data))
    } else {
      console.error('WebSocket is not open. Ready state:', this.ws.readyState)
    }
  }

  onOpen() {
    // 用户可以在这里定义连接成功时的行为
    console.log('Custom onOpen handler called')
  }

  onMessage(message) {
    // 用户可以在这里定义消息接收时的行为
    console.log('Custom onMessage handler called with message:', message)
  }

  onError(error) {
    // 用户可以在这里定义错误发生时的行为
    console.error('Custom onError handler called with error:', error)
  }
}
export default WebSocketClient
